package com.shermanzhou.freemarker;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhouchaoqun
 * @date 2018/11/22 上午10:13
 */
public class FreemarkerTest {
    public static void main(String[] args) throws Exception {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        File templateDir = new File(FreemarkerTest.class.getClassLoader().getResource("templates").toURI());
        cfg.setDirectoryForTemplateLoading(templateDir);
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);


        List<Student> students = new ArrayList<>();
        students.add(new Student("Li lei"));
        students.add(new Student("Han meimei"));

        Map<String, Object> root = new HashMap<>();
        root.put("students", students);


        Template template = cfg.getTemplate("person.ftl");

        OutputStream outputStream = new FileOutputStream("demo-freemarker/src/main/java/person.txt");
        System.out.println(outputStream);
        Writer out = new OutputStreamWriter(outputStream);
        template.process(root, out);
    }

    public static class Student {
        private String name;

        private Student(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
